package com.demon.net

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import io.reactivex.Flowable
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.subscribers.ResourceSubscriber

interface RpcCallManager {
  fun <T> manageRpcCall(
    flowable: Flowable<T>,
    subscribe: ResourceSubscriber<T>
  )

  class RpcCallManagerImpl : RpcCallManager,LifecycleObserver {

    private val mCompositeSubscription = CompositeDisposable()

    override fun <T> manageRpcCall(
      flowable: Flowable<T>,
      subscribe: ResourceSubscriber<T>
    ) {
      mCompositeSubscription.add(
          flowable.observeOn(
              io.reactivex.android.schedulers
                  .AndroidSchedulers.mainThread()
          ).subscribeWith(subscribe)
      )
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun unSubscribeAll() {
      mCompositeSubscription.dispose()
    }
  }
}